package cn.iocoder.yudao.module.project.controller.admin.orderdetail;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.iocoder.yudao.framework.common.exception.ServiceException;
import cn.iocoder.yudao.module.project.dal.dataobject.order.OrderDO;
import cn.iocoder.yudao.module.project.dal.mysql.deliveryreceiptdetail.DeliveryReceiptDetailMapper;
import cn.iocoder.yudao.module.project.dal.mysql.order.OrderMapper;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.ObjectUtils;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.constraints.*;
import javax.validation.*;
import javax.servlet.http.*;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.io.IOException;
import java.util.stream.Collectors;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.error;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import static cn.iocoder.yudao.module.project.config.projectDefine.HTTP_STATUS.ERROR_STATUS;
import static cn.iocoder.yudao.module.project.config.projectDefine.ORDER_TYPE.*;

import cn.iocoder.yudao.module.project.controller.admin.orderdetail.vo.*;
import cn.iocoder.yudao.module.project.dal.dataobject.orderdetail.OrderDetailDO;
import cn.iocoder.yudao.module.project.service.orderdetail.OrderDetailService;
import org.springframework.web.multipart.MultipartFile;

@Tag(name = "管理后台 - 生产订单详情")
@RestController
@RequestMapping("/project/order-detail")
@Validated
@Slf4j
public class OrderDetailController {

    @Resource
    private OrderDetailService orderDetailService;

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private DeliveryReceiptDetailMapper deliveryReceiptDetailMapper;

    @PostMapping("/create")
    @Operation(summary = "创建生产订单详情")
    // @PreAuthorize("@ss.hasPermission('project:order-detail:create')")
    public CommonResult<String> createOrderDetail(@Valid @RequestBody OrderDetailSaveReqVO createReqVO) {
        return success(orderDetailService.createOrderDetail(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新生产订单详情")
    // @PreAuthorize("@ss.hasPermission('project:order-detail:update')")
    public CommonResult<Boolean> updateOrderDetail(@Valid @RequestBody OrderDetailSaveReqVO updateReqVO) {
        orderDetailService.updateOrderDetail(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除生产订单详情")
    @Parameter(name = "id", description = "编号", required = true)
    // @PreAuthorize("@ss.hasPermission('project:order-detail:delete')")
    public CommonResult<Boolean> deleteOrderDetail(@RequestParam("id") String id) {
        orderDetailService.deleteOrderDetail(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得生产订单详情")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    // @PreAuthorize("@ss.hasPermission('project:order-detail:query')")
    public CommonResult<OrderDetailRespVO> getOrderDetail(@RequestParam("id") String id) {
        OrderDetailDO orderDetail = orderDetailService.getOrderDetail(id);
        return success(BeanUtils.toBean(orderDetail, OrderDetailRespVO.class));
    }

    @PostMapping("/page")
    @Operation(summary = "获得生产订单详情分页")
    @PreAuthorize("@ss.hasPermission('project:order-detail:query')")
    public CommonResult<PageResult<OrderDetailRespVO>> getOrderDetailPage(@Valid @RequestBody OrderDetailPageReqVO pageReqVO) {
        PageResult<OrderDetailDO> pageResult = orderDetailService.getOrderDetailPage(pageReqVO);
        PageResult<OrderDetailRespVO> result = BeanUtils.toBean(pageResult, OrderDetailRespVO.class);
        if (null != result) {
            List<OrderDetailRespVO> list = result.getList();
            if (CollectionUtil.isNotEmpty(list)) {
                for (OrderDetailRespVO orderDetailRespVO : list) {
                    LocalDateTime createTime = orderDetailRespVO.getCreateTime();
                    String expiryDate = orderDetailRespVO.getExpiryDate();
                    String createTimeStr = DateUtil.format(createTime, "yyyy-MM-dd HH:mm:ss");
                    // String expiryDateStr = DateUtil.format(expiryDate, "yyyy-MM-dd");
                    orderDetailRespVO.setCreateTimeStr(createTimeStr);
                    orderDetailRespVO.setExpiryDateStr(expiryDate);
                }
            }
        }
        return success(result);
    }

    // @GetMapping("/export-excel")
    // @Operation(summary = "导出生产订单详情 Excel")
    // @PreAuthorize("@ss.hasPermission('project:order-detail:export')")
    // @ApiAccessLog(operateType = EXPORT)
    // public void exportOrderDetailExcel(@Valid OrderDetailPageReqVO pageReqVO,
    //           HttpServletResponse response) throws IOException {
    //     pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
    //     List<OrderDetailDO> list = orderDetailService.getOrderDetailPage(pageReqVO).getList();
    //     // 导出 Excel
    //     ExcelUtils.write(response, "生产订单详情.xls", "数据", OrderDetailRespVO.class,
    //                     BeanUtils.toBean(list, OrderDetailRespVO.class));
    // }




    @Operation(summary = "导出生产订单模板 Excel")
    @GetMapping(value = "/exportTemplate")
    @PreAuthorize("@ss.hasPermission('project:order-detail:export')")
    public void exportTemplate(HttpServletResponse response,String orderType){
        InputStream inputStream = null;
        String fileName = "生产订单导入模板.xlsx";
        try {
            String path = "/template/生产订单批量模板标准.xlsx";
            if (StringUtils.equals(ORDER_TYPE_1, orderType)) {
                path = "/template/生产订单批量模板标准.xlsx";
                fileName = "生产订单批量模板标准.xlsx";
            }
            if (StringUtils.equals(ORDER_TYPE_2, orderType)) {
                path = "/template/生产订单批量模板自定义.xlsx";
                fileName = "生产订单批量模板自定义.xlsx";
            }
            if(StringUtils.equals(ORDER_TYPE_6, orderType)){
                path = "/template/组合模板.xlsx";
                fileName = "组合模板.xlsx";
            }
            ClassPathResource classPathResource = new ClassPathResource(path);
            inputStream = classPathResource.getInputStream();
            Workbook excel = WorkbookFactory.create(inputStream);

            //使用输出流进行表格下载,基于浏览器作为客户端下载
            OutputStream out = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");//代表的是Excel文件类型
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));;//指定以附件形式进行下载
            excel.write(out);
            out.flush();
            out.close();
            excel.close();
        } catch (Exception e) {
        } finally {
            IoUtil.close(inputStream);
        }
    }

    @PutMapping("/edit")
    @Operation(summary = "编辑生产订单明细")
    public CommonResult<Boolean> editOrderDetail(@Valid @RequestBody OrderDetailSaveReqVO updateReqVO) {
        orderDetailService.editOrderDetail(updateReqVO);
        return success(true);
    }

    @PostMapping("/importOrder")
    @Operation(summary = "导入生产订单 Excel")
    @PreAuthorize("@ss.hasPermission('project:order-detail:import')")
    public CommonResult<String> importOrder(@RequestParam("file") List<MultipartFile> fileList,@RequestParam("orderType") String orderType) {

        String msg = "";
        try {
            for(MultipartFile file : fileList){
                long start = System.currentTimeMillis();
                ExcelReader excelReader = ExcelUtil.getReader(file.getInputStream());
                Sheet sheet = excelReader.getSheet();
                List<List<Object>> list = excelReader.read();

                if (CollectionUtil.isNotEmpty(list)) {
                    if (list.size() > 7) {
                        List<OrderDetailDO> importDataList = new ArrayList<>();

                        OrderDO orderDO = new OrderDO();

                        if (StringUtils.equals(orderType, ORDER_TYPE_1)) {
                            this.parseOrderOneV2(orderDO, list, importDataList);
                        }
                        if (StringUtils.equals(orderType, ORDER_TYPE_2)) {
                            this.parseOrderTwoV2(orderDO, list, importDataList);
                        }
                        if(StringUtils.equals(orderType, ORDER_TYPE_6)){
                            this.parseOrderTwoV6(orderDO, list, importDataList);
                        }

                        importDataList = importDataList.stream()
                                .filter(c -> null != c.getId())
                                .collect(Collectors.toList());

                        if (CollectionUtil.isNotEmpty(importDataList)) {
                            List<String> ids = importDataList.stream()
                                    .map(c -> {
                                        return c.getId();
                                    })
                                    .distinct()
                                    .collect(Collectors.toList());
                            Map<String, Object> params = new HashMap<>();
                            params.put("ids", ids);

                            // 查询已经存在的生产订单数据,这些将不再写入库中
                            List<OrderDetailDO> savedList = orderDetailService.selectSavedList(params);
                            List<OrderDetailDO> updateList = new ArrayList<OrderDetailDO>();
                            List<OrderDetailDO> insertList = new ArrayList<OrderDetailDO>();

                            for (OrderDetailDO record : importDataList) {
                                boolean issaved = false;

                                if (null != savedList && savedList.size() > 0) {
                                    for (OrderDetailDO saved : savedList) {
                                        if (
                                                saved.getId().equals(record.getId())
                                        ) {
                                            record.setId(saved.getId());
                                            updateList.add(record);
                                            issaved = true;
                                            break;
                                        }
                                    }

                                }

                                if (!issaved) {
                                    insertList.add(record);
                                }
                            }

                            orderDetailService.insertRecord(insertList);
                            orderDetailService.updateRecord(updateList);
                            System.out.println("取excel完毕：" +(System.currentTimeMillis() - start)+"}毫秒");

                            LongSummaryStatistics longSummaryStatistics = importDataList.stream()
                                    .filter(c -> null != c.getNum())
                                    .mapToLong(OrderDetailDO::getNum).summaryStatistics();

                            long totalNum = longSummaryStatistics.getSum();
                            orderDO.setDeleted(false);
                            orderDO.setTotalNum(totalNum);
                            OrderDO order = orderMapper.selectById(orderDO.getId());
                            if (null == order) {
                                orderMapper.insert(orderDO);
                            }
                            if (null != order) {
                                orderMapper.updateById(orderDO);
                            }

                        }

                        msg = importDataList.size() + "条记录导入成功";
                    }

                }
            }
        }
        catch (ServiceException se) {
            log.error(se.getMessage());
            return error(ERROR_STATUS, se.getMessage());
        }
        catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new ServiceException(ERROR_STATUS, "导入生产订单失败");
        }
        return success(msg);
    }

    private Object warpperFieldValue(Class fieldType, Object value) {
        if(fieldType == String.class){
            return String.valueOf(value);
        } else if(fieldType == Integer.class){
            return Integer.valueOf(value.toString());
        } else if(fieldType == Long.class){
            return Long.valueOf(value.toString());
        } else if(fieldType == Double.class){
            return Double.valueOf(value.toString());
        } else if(fieldType == Date.class){
            return DateUtil.parseDate(value.toString());
        }
        return value;
    }

    public void processExcelData(OrderDO orderDO, List<List<Object>> excelDataList, List<OrderDetailDO> orderDetailDOList) {
        List<Object> headerRow = excelDataList.get(1);
        ClassPathResource resource = new ClassPathResource("config/import-field-mapping.json");
        String jonStr = null;
        try{
            jonStr = IoUtil.readUtf8(resource.getInputStream());
        }catch (IOException e){
            throw new ServiceException(ERROR_STATUS, "导入生产订单失败[读取配置信息失败]");
        }


        JSONObject jsonObject = JSONObject.parseObject(jonStr);
        JSONArray mappings = jsonObject.getJSONObject("orderDetail").getJSONArray("mappings");

        Map<Integer, JSONObject> excelHeaderIndexMapping = new HashMap<>();

        for(int i = 0; i < mappings.size(); i++){
            JSONObject mapping = mappings.getJSONObject(i);
            String excelHeaderName = mapping.getString("excelHeaderName");
            int index = headerRow.indexOf(excelHeaderName);
            excelHeaderIndexMapping.put(index, mapping);
        }


        int startRowIndex = 2;
        for(int i = startRowIndex; i < excelDataList.size() - 1; i++){
            OrderDetailDO orderDetailDO = new OrderDetailDO();

            List<Object> dataRow = excelDataList.get(i);

            if(i == startRowIndex){
                if(!ObjectUtils.isEmpty(dataRow.get(0))){
                    if(dataRow.get(0) instanceof String){
                        String shippingDateStr = dataRow.get(0).toString();
                        LocalDateTime shippingDate = DateUtil.parse(shippingDateStr, "yyyy/MM/dd").toLocalDateTime();
                        orderDO.setShippingDate(shippingDate);
                    }else{
                        DateTime dateTime = (DateTime) dataRow.get(0);
                        orderDO.setShippingDate(dateTime.toLocalDateTime());
                    }
                }
                if(!ObjectUtils.isEmpty(dataRow.get(1))){
                    orderDO.setCustomerName(dataRow.get(1).toString());
                }

                if(!ObjectUtils.isEmpty(dataRow.get(2))){
                    orderDO.setCode(dataRow.get(2).toString());
                }
            }


            for(int j = 0; j < dataRow.size(); j++){
                Object value = dataRow.get(j);
                JSONObject mapping = excelHeaderIndexMapping.get(j);

                if(mapping == null){
                    continue;
                }

                if(value == null){
                    continue;
                }

                String beanField = mapping.getString("beanField");
                Field field = ReflectionUtils.findField(OrderDetailDO.class, beanField);
                if(field == null){
                    continue;
                }
                field.setAccessible(true);

                Class fieldType = field.getType();

                Object warpperValue = warpperFieldValue(fieldType, value);

                ReflectionUtils.setField(field, orderDetailDO, warpperValue);
            }
            orderDetailDOList.add(orderDetailDO);
        }
    }

    private OrderDO parseOrderTwoV6(OrderDO orderDO, List<List<Object>> list, List<OrderDetailDO> importDataList) {
        // 订单导入日期
        LocalDate localDate = LocalDate.now();
        LocalDateTime orderDateTime = localDate.atTime(0, 0, 0);
        orderDO.setOrderDate(orderDateTime);

        processExcelData(orderDO, list, importDataList);

        Comparator<OrderDetailDO> comparator = Comparator.comparing(OrderDetailDO::getLen).thenComparing(OrderDetailDO::getFlex);

        importDataList = importDataList.stream().sorted(comparator).collect(Collectors.toList());

        OrderDetailDO tempOrderDetailDO = importDataList.get(0);
        Object orderCode = tempOrderDetailDO.getOrderCode();
        orderDO.setId(orderCode.toString());

        OrderDO existOrderDO = orderMapper.selectById(orderDO.getId());
        if(null != existOrderDO){
            throw new ServiceException(ERROR_STATUS, "订单编号已存在");
        }

        orderDO.setDateStr(tempOrderDetailDO.getExpiryDate());

        // 统一设置订单明细的订单编号
        int partIdIndex = 1;
        for (OrderDetailDO orderDetailDO : importDataList) {
            orderDetailDO.setId(orderDO.getId()+"_"+orderDO.getId() + String.format("%03d", partIdIndex));
            orderDetailDO.setPartId(orderDO.getId() + String.format("%03d", partIdIndex));
            orderDetailDO.setOrderCode(orderCode.toString());
            orderDetailDO.setDetailInfoJson(JSONObject.toJSONString(orderDetailDO));
            partIdIndex++;
        }

        return orderDO;

    }

    // 解析批量模板标准
    private OrderDO parseOrderOne(OrderDO orderDO, List<List<Object>> list, List<OrderDetailDO> importDataList) {
        // 订单导入日期
        LocalDate localDate = LocalDate.now();
        LocalDateTime orderDateTime = localDate.atTime(0, 0, 0);
        orderDO.setOrderDate(orderDateTime);

        // 从第四行开始读取,一直到倒数第4行都是生产订单
        // 设置第n行有订单编号
        Integer orderCodeLine = 0;
        for (int i = 2; i < list.size() - 3; i++) {
            OrderDetailDO orderDetailDO = new OrderDetailDO();
            // OrderDetailDO.setOrderCode(orderCodeStr);

            // line
            Object line = list.get(i).get(0);
            if (line != null) {
                if (line.toString().contains("line")
                        || line.toString().contains("Line")
                ) {
                    orderCodeLine = i - 1;
                    continue;
                }

                if (!NumberUtil.isNumber(line.toString())) {
                    continue;
                }
            }

            if (line == null || StringUtils.isBlank(line.toString())) {
                continue;
            }

            // 产品名称
            Object name = list.get(i).get(1);
            if (name != null && !name.equals("")) {
                orderDetailDO.setName(name.toString());
            }

            // partID
            Object partId = list.get(i).get(3);
            if (partId != null && !partId.equals("")) {
                orderDetailDO.setPartId(partId.toString());
                // OrderDetailDO.setId(orderCodeStr + "_" + partId.toString());
            }

            // 型号
            Object flex = list.get(i).get(4);
            if (flex != null && !flex.equals("")) {
                orderDetailDO.setFlex(flex.toString());
            }

            // 长度
            Object len = list.get(i).get(5);
            if (len != null && !len.equals("")) {
                if (NumberUtil.isNumber(len.toString())) {
                    orderDetailDO.setLen(Double.valueOf(len.toString()));
                }
            }

            // JR/INT/SR
            Object type = list.get(i).get(6);
            if (type != null && !type.equals("")) {
                orderDetailDO.setType(type.toString());
            }

            // 数量
            Object num = list.get(i).get(7);
            if (num != null && !num.equals("")) {
                if (NumberUtil.isNumber(num.toString())) {
                    orderDetailDO.setNum(Long.valueOf(num.toString()));
                }
            }

            // C课交期
            Object expiryDate = list.get(i).get(8);
            if (expiryDate != null && !expiryDate.equals("")) {
                // DateTime parseDateTime = DateUtil.parse(expiryDate.toString());
                // LocalDateTime dateTime = parseDateTime.toLocalDateTime();
                orderDetailDO.setExpiryDate(expiryDate.toString());
            }

            // eanCode
            Object eanCode = list.get(i).get(9);
            if (eanCode != null && !eanCode.equals("")) {
                orderDetailDO.setEanCode(eanCode.toString());
            }

            // 图档名
            Object drawing = list.get(i).get(10);
            if (drawing != null && !drawing.equals("")) {
                orderDetailDO.setDrawing(drawing.toString());
            }

            // 面漆
            Object topcoat = list.get(i).get(11);
            if (topcoat != null && !topcoat.equals("")) {
                orderDetailDO.setTopcoat(topcoat.toString());
            }
            orderDetailDO.setDeleted(false);
            importDataList.add(orderDetailDO);
        }

        // 解析订单编号和订单日期
        // 订单编号
        Object orderCode = list.get(orderCodeLine).get(0);
        String orderCodeStr = "";
        if (orderCode != null && !orderCode.equals("")) {
            // orderCodeStr = orderCode.toString().replaceAll("[^\\d]", "");
            orderCodeStr = orderCode.toString().replace("：",":").replaceAll("\\s", "");
            String[] orderCodeArr = orderCodeStr.split(":");
            if (orderCodeArr.length == 2) {
                orderDO.setId(orderCodeArr[1]);
            }
            if (StringUtils.isBlank(orderDO.getId())) {
                throw new ServiceException(ERROR_STATUS, "订单编号不能为空");
            }
        }

        // 订单日期
        Object dateStr = list.get(orderCodeLine).get(4);
        if (dateStr != null && !dateStr.equals("")) {
            String orderDateStr = dateStr.toString()
                    .replace("日期:", "")
                    .replaceAll("\\s*", "");
            orderDO.setDateStr(orderDateStr);
        }

        // 解析到货点,出货方式,厂长,开发业务,经办
        // 设置第n行有到货点
        Integer managerLine = list.size() - 2;
        for (int i = 2; i < list.size(); i++) {
            // 过滤掉列数小的
            if (list.get(i).size() < 8) {
                continue;
            }

            Object manager = list.get(i).get(9);
            if (manager != null) {
                if (manager.toString().contains("厂长")
                ) {
                    managerLine = i;
                    break;
                }
            }
        }

        // 到货点
        Object arrivalPoint = list.get(managerLine - 1).get(10);
        if (arrivalPoint != null && !arrivalPoint.equals("")) {
            orderDO.setArrivalPoint(arrivalPoint.toString());
        }

        // 出货方式
        Object deliveryMode = list.get(managerLine - 1).get(11);
        if (deliveryMode != null && !deliveryMode.equals("")) {
            orderDO.setDeliveryMode(deliveryMode.toString());
        }

        // 厂长
        Object manager = list.get(managerLine + 1).get(9);
        if (manager != null && !manager.equals("")) {
            orderDO.setManager(manager.toString());
        }

        // 开发业务
        Object businessName = list.get(managerLine + 1).get(10);
        if (businessName != null && !businessName.equals("")) {
            orderDO.setBusinessName(businessName.toString());
        }

        // 经办
        Object operator = list.get(managerLine + 1).get(11);
        if (operator != null && !operator.equals("")) {
            orderDO.setOperator(operator.toString());
        }

        // 统一设置订单明细的订单编号
        for (OrderDetailDO orderDetailDO : importDataList) {
            orderDetailDO.setOrderCode(orderDO.getId());
            orderDetailDO.setId(orderDO.getId() + "_" + orderDetailDO.getPartId());
        }

        return orderDO;
    }

    private OrderDO parseOrderOneV2(OrderDO orderDO, List<List<Object>> list, List<OrderDetailDO> importDataList) {
        // 订单导入日期
        LocalDate localDate = LocalDate.now();
        LocalDateTime orderDateTime = localDate.atTime(0, 0, 0);
        orderDO.setOrderDate(orderDateTime);

        // 从第四行开始读取,一直到倒数第4行都是生产订单
        // 设置第n行有订单编号
        Integer orderCodeLine = 0;
        for (int i = 2; i < list.size() - 3; i++) {
            OrderDetailDO orderDetailDO = new OrderDetailDO();
            // OrderDetailDO.setOrderCode(orderCodeStr);

            // line
            Object line = list.get(i).get(0);
            if (line != null) {
                if (line.toString().contains("line")
                        || line.toString().contains("Line")
                ) {
                    orderCodeLine = i - 1;
                    continue;
                }

                if (!NumberUtil.isNumber(line.toString())) {
                    continue;
                }
            }

            if (line == null || StringUtils.isBlank(line.toString())) {
                continue;
            }

            // 产品名称
            Object name = list.get(i).get(1);
            if (name != null && !name.equals("")) {
                orderDetailDO.setName(name.toString());
            }

            // partID
            Object partId = list.get(i).get(3);
            if (partId != null && !partId.equals("")) {
                orderDetailDO.setPartId(partId.toString());
                // OrderDetailDO.setId(orderCodeStr + "_" + partId.toString());
            }

            // 型号
            Object flex = list.get(i).get(4);
            if (flex != null && !flex.equals("")) {
                orderDetailDO.setFlex(flex.toString());
            }

            // 长度
            Object len = list.get(i).get(5);
            if (len != null && !len.equals("")) {
                if (NumberUtil.isNumber(len.toString())) {
                    orderDetailDO.setLen(Double.valueOf(len.toString()));
                }
            }

            // JR/INT/SR
            Object type = list.get(i).get(6);
            if (type != null && !type.equals("")) {
                orderDetailDO.setType(type.toString());
            }

            // 数量
            Object num = list.get(i).get(8);
            if (num != null && !num.equals("")) {
                if (NumberUtil.isNumber(num.toString())) {
                    orderDetailDO.setNum(Long.valueOf(num.toString()));
                }
            }

            // C课交期
            Object expiryDate = list.get(i).get(9);
            if (expiryDate != null && !expiryDate.equals("")) {
                // DateTime parseDateTime = DateUtil.parse(expiryDate.toString());
                // LocalDateTime dateTime = parseDateTime.toLocalDateTime();
                orderDetailDO.setExpiryDate(expiryDate.toString());
            }

            // eanCode
            Object eanCode = list.get(i).get(11);
            if (eanCode != null && !eanCode.equals("")) {
                orderDetailDO.setEanCode(eanCode.toString());
            }

            // // 图档名
            // Object drawing = list.get(i).get(10);
            // if (drawing != null && !drawing.equals("")) {
            //     orderDetailDO.setDrawing(drawing.toString());
            // }

            // 面漆
            Object topcoat = list.get(i).get(12);
            if (topcoat != null && !topcoat.equals("")) {
                orderDetailDO.setTopcoat(topcoat.toString());
            }
            orderDetailDO.setDeleted(false);
            importDataList.add(orderDetailDO);
        }

        // 解析订单编号和订单日期
        // 订单编号
        Object orderCode = list.get(orderCodeLine).get(0);
        String orderCodeStr = "";
        if (orderCode != null && !orderCode.equals("")) {
            // orderCodeStr = orderCode.toString().replaceAll("[^\\d]", "");
            orderCodeStr = orderCode.toString().replace("：",":").replaceAll("\\s", "");
            String[] orderCodeArr = orderCodeStr.split(":");
            if (orderCodeArr.length == 2) {
                orderDO.setId(orderCodeArr[1]);
            }
            if (StringUtils.isBlank(orderDO.getId())) {
                throw new ServiceException(ERROR_STATUS, "订单编号不能为空");
            }
        }

        for (OrderDetailDO orderDetailDO : importDataList) {
            orderDetailDO.setOrderCode(orderDO.getId());
            orderDetailDO.setFullFlexName(orderDetailDO.getFlex());
            orderDetailDO.setDetailInfoJson(JSONObject.toJSONString(orderDetailDO));
        }

        // 订单日期
        Object dateStr = list.get(orderCodeLine).get(4);
        if (dateStr != null && !dateStr.equals("")) {
            String orderDateStr = dateStr.toString()
                    .replace("日期:", "")
                    .replaceAll("\\s*", "");
            orderDO.setDateStr(orderDateStr);
        }

        // 编号
        Object code = list.get(orderCodeLine).get(12);
        if (code != null && !code.equals("")) {
            orderDO.setCode(code.toString());
        }

        // 解析到货点,出货方式,厂长,开发业务,经办
        // 设置第n行有到货点
        Integer managerLine = list.size() - 2;
        for (int i = 2; i < list.size(); i++) {
            // 过滤掉列数小的
            if (list.get(i).size() < 8) {
                continue;
            }

            Object manager = list.get(i).get(10);
            if (manager != null) {
                if (manager.toString().contains("厂长")
                ) {
                    managerLine = i;
                    break;
                }
            }
        }

        // 解析备注
        // 设置第n行有备注
        Integer remarkLine = list.size() - 2;
        for (int i = 2; i < list.size(); i++) {
            Object remark = list.get(i).get(0);
            if (remark != null) {
                if (remark.toString().contains("備註")
                ) {
                    String remarkStr = remark.toString()
                            .replace("備註", "")
                            .replace(":", "")
                            .replace("：", "")
                            .trim()
                            ;
                    orderDO.setRemark(remarkStr);
                    remarkLine = i;
                    break;
                }
            }
        }

        // 到货点
        Object arrivalPoint = list.get(managerLine - 1).get(11);
        if (arrivalPoint != null && !arrivalPoint.equals("")) {
            orderDO.setArrivalPoint(arrivalPoint.toString());
        }

        // 出货方式
        Object deliveryMode = list.get(managerLine - 1).get(12);
        if (deliveryMode != null && !deliveryMode.equals("")) {
            orderDO.setDeliveryMode(deliveryMode.toString());
        }

        // 厂长
        Object manager = list.get(managerLine + 1).get(10);
        if (manager != null && !manager.equals("")) {
            orderDO.setManager(manager.toString());
        }

        // 开发业务
        Object businessName = list.get(managerLine + 1).get(11);
        if (businessName != null && !businessName.equals("")) {
            orderDO.setBusinessName(businessName.toString());
        }

        // 经办
        Object operator = list.get(managerLine + 1).get(12);
        if (operator != null && !operator.equals("")) {
            orderDO.setOperator(operator.toString());
        }

        // 统一设置订单明细的订单编号
        for (OrderDetailDO orderDetailDO : importDataList) {
            orderDetailDO.setOrderCode(orderDO.getId());
            orderDetailDO.setId(orderDO.getId() + "_" + orderDetailDO.getPartId());
        }

        return orderDO;
    }

    // 解析批量模板自定义
    private OrderDO parseOrderTwo(OrderDO orderDO, List<List<Object>> list, List<OrderDetailDO> importDataList) {
        // 订单导入日期
        LocalDate localDate = LocalDate.now();
        LocalDateTime orderDateTime = localDate.atTime(0, 0, 0);
        orderDO.setOrderDate(orderDateTime);

        // 从第四行开始读取,一直到倒数第4行都是生产订单
        // 设置第n行有订单编号
        Integer orderCodeLine = 0;
        for (int i = 2; i < list.size() - 3; i++) {
            OrderDetailDO orderDetailDO = new OrderDetailDO();
            // OrderDetailDO.setOrderCode(orderCodeStr);

            // line
            Object line = list.get(i).get(0);
            if (line != null) {
                if (line.toString().contains("line")
                        || line.toString().contains("Line")
                ) {
                    orderCodeLine = i - 1;
                    continue;
                }

                if (!NumberUtil.isNumber(line.toString())) {
                    continue;
                }
            }

            if (line == null || StringUtils.isBlank(line.toString())) {
                continue;
            }

            // 产品名称
            Object name = list.get(i).get(1);
            if (name != null && !name.equals("")) {
                orderDetailDO.setName(name.toString());
            }

            // partID
            Object partId = list.get(i).get(3);
            if (partId != null && !partId.equals("")) {
                orderDetailDO.setPartId(partId.toString());
                // OrderDetailDO.setId(orderCodeStr + "_" + partId.toString());
            }

            // 型号
            Object flex = list.get(i).get(4);
            if (flex != null && !flex.equals("")) {
                orderDetailDO.setFlex(flex.toString());
            }

            // 长度
            Object len = list.get(i).get(5);
            if (len != null && !len.equals("")) {
                if (NumberUtil.isNumber(len.toString())) {
                    orderDetailDO.setLen(Double.valueOf(len.toString()));
                }
            }

            // JR/INT/SR
            Object type = list.get(i).get(6);
            if (type != null && !type.equals("")) {
                orderDetailDO.setType(type.toString());
            }

            // 数量
            Object num = list.get(i).get(7);
            if (num != null && !num.equals("")) {
                if (NumberUtil.isNumber(num.toString())) {
                    orderDetailDO.setNum(Long.valueOf(num.toString()));
                }
            }

            // C课交期
            Object expiryDate = list.get(i).get(8);
            if (expiryDate != null && !expiryDate.equals("")) {
                // DateTime parseDateTime = DateUtil.parse(expiryDate.toString());
                // LocalDateTime dateTime = parseDateTime.toLocalDateTime();
                orderDetailDO.setExpiryDate(expiryDate.toString());
            }

            // eanCode
            Object eanCode = list.get(i).get(9);
            if (eanCode != null && !eanCode.equals("")) {
                orderDetailDO.setEanCode(eanCode.toString());
            }

            // 图档名
            Object drawing = list.get(i).get(10);
            if (drawing != null && !drawing.equals("")) {
                orderDetailDO.setDrawing(drawing.toString());
            }

            // 面漆
            Object topcoat = list.get(i).get(11);
            if (topcoat != null && !topcoat.equals("")) {
                orderDetailDO.setTopcoat(topcoat.toString());
            }
            orderDetailDO.setDeleted(false);
            importDataList.add(orderDetailDO);
        }

        // 解析到货点,出货方式,厂长,开发业务,经办
        // 设置第n行有到货点
        Integer managerLine = list.size() - 2;
        for (int i = 2; i < list.size(); i++) {
            Object manager = list.get(i).get(9);
            if (manager != null) {
                if (manager.toString().contains("厂长")
                ) {
                    managerLine = i;
                    break;
                }
            }
        }

        // 到货点
        Object arrivalPoint = list.get(managerLine - 1).get(10);
        if (arrivalPoint != null && !arrivalPoint.equals("")) {
            orderDO.setArrivalPoint(arrivalPoint.toString());
        }

        // 出货方式
        Object deliveryMode = list.get(managerLine - 1).get(11);
        if (deliveryMode != null && !deliveryMode.equals("")) {
            orderDO.setDeliveryMode(deliveryMode.toString());
        }

        // 厂长
        Object manager = list.get(managerLine + 1).get(9);
        if (manager != null && !manager.equals("")) {
            orderDO.setManager(manager.toString());
        }

        // 开发业务
        Object businessName = list.get(managerLine + 1).get(10);
        if (businessName != null && !businessName.equals("")) {
            orderDO.setBusinessName(businessName.toString());
        }

        // 经办
        Object operator = list.get(managerLine + 1).get(11);
        if (operator != null && !operator.equals("")) {
            orderDO.setOperator(operator.toString());
        }

        // 解析订单编号和订单日期
        // 订单编号
        Object orderCode = list.get(orderCodeLine).get(0);
        String orderCodeStr = "";
        if (orderCode != null && !orderCode.equals("")) {
            // orderCodeStr = orderCode.toString().replaceAll("[^\\d]", "");
            orderCodeStr = orderCode.toString().replace("：",":").replaceAll("\\s", "");
            String[] orderCodeArr = orderCodeStr.split(":");
            if (orderCodeArr.length == 2) {
                orderDO.setId(orderCodeArr[1]);
            }
            if (StringUtils.isBlank(orderDO.getId())) {
                throw new ServiceException(ERROR_STATUS, "订单编号不能为空");
            }
        }

        // 订单日期
        Object dateStr = list.get(orderCodeLine).get(4);
        if (dateStr != null && !dateStr.equals("")) {
            String orderDateStr = dateStr.toString()
                    .replace("日期:", "")
                    .replaceAll("\\s*", "");
            orderDO.setDateStr(orderDateStr);
        }

        // 统一设置订单明细的订单编号
        for (OrderDetailDO orderDetailDO : importDataList) {
            orderDetailDO.setOrderCode(orderDO.getId());
            orderDetailDO.setId(orderDO.getId() + "_" + orderDetailDO.getPartId());
        }

        return orderDO;
    }

    private OrderDO parseOrderTwoV2(OrderDO orderDO, List<List<Object>> list, List<OrderDetailDO> importDataList) {
        // 订单导入日期
        LocalDate localDate = LocalDate.now();
        LocalDateTime orderDateTime = localDate.atTime(0, 0, 0);
        orderDO.setOrderDate(orderDateTime);

        // 从第四行开始读取,一直到倒数第4行都是生产订单
        // 设置第n行有订单编号
        Integer orderCodeLine = 0;
        for (int i = 2; i < list.size() - 3; i++) {
            OrderDetailDO orderDetailDO = new OrderDetailDO();
            // OrderDetailDO.setOrderCode(orderCodeStr);

            // line
            Object line = list.get(i).get(0);
            if (line != null) {
                if (line.toString().contains("line")
                        || line.toString().contains("Line")
                ) {
                    orderCodeLine = i - 1;
                    continue;
                }

                if (!NumberUtil.isNumber(line.toString())) {
                    continue;
                }
            }

            if (line == null || StringUtils.isBlank(line.toString())) {
                continue;
            }

            // 产品名称
            Object name = list.get(i).get(1);
            if (name != null && !name.equals("")) {
                orderDetailDO.setName(name.toString());
            }

            // partID
            Object partId = list.get(i).get(3);
            if (partId != null && !partId.equals("")) {
                orderDetailDO.setPartId(partId.toString());
                // OrderDetailDO.setId(orderCodeStr + "_" + partId.toString());
            }

            // 型号
            Object flex = list.get(i).get(4);
            if (flex != null && !flex.equals("")) {
                orderDetailDO.setFlex(flex.toString());
            }

            // 长度
            Object len = list.get(i).get(5);
            if (len != null && !len.equals("")) {
                if (NumberUtil.isNumber(len.toString())) {
                    orderDetailDO.setLen(Double.valueOf(len.toString()));
                }
            }

            // JR/INT/SR
            Object type = list.get(i).get(6);
            if (type != null && !type.equals("")) {
                orderDetailDO.setType(type.toString());
            }

            // 数量
            Object num = list.get(i).get(7);
            if (num != null && !num.equals("")) {
                if (NumberUtil.isNumber(num.toString())) {
                    orderDetailDO.setNum(Long.valueOf(num.toString()));
                }
            }

            // C课交期
            Object expiryDate = list.get(i).get(8);
            if (expiryDate != null && !expiryDate.equals("")) {
                // DateTime parseDateTime = DateUtil.parse(expiryDate.toString());
                // LocalDateTime dateTime = parseDateTime.toLocalDateTime();
                orderDetailDO.setExpiryDate(expiryDate.toString());
            }

            // eanCode
            Object eanCode = list.get(i).get(9);
            if (eanCode != null && !eanCode.equals("")) {
                orderDetailDO.setEanCode(eanCode.toString());
            }

            // 图档名
            Object drawing = list.get(i).get(10);
            if (drawing != null && !drawing.equals("")) {
                orderDetailDO.setDrawing(drawing.toString());
            }

            // 面漆
            Object topcoat = list.get(i).get(11);
            if (topcoat != null && !topcoat.equals("")) {
                orderDetailDO.setTopcoat(topcoat.toString());
            }
            orderDetailDO.setDeleted(false);
            importDataList.add(orderDetailDO);
        }

        // 解析到货点,出货方式,厂长,开发业务,经办
        // 设置第n行有到货点
        Integer managerLine = list.size() - 2;
        for (int i = 2; i < list.size(); i++) {
            Object manager = list.get(i).get(9);
            if (manager != null) {
                if (manager.toString().contains("厂长")
                ) {
                    managerLine = i;
                    break;
                }
            }
        }

        // 解析备注
        // 设置第n行有备注
        Integer remarkLine = list.size() - 2;
        for (int i = 2; i < list.size(); i++) {
            Object remark = list.get(i).get(0);
            if (remark != null) {
                if (remark.toString().contains("備註")
                ) {
                    String remarkStr = remark.toString()
                            .replace("備註", "")
                            .replace(":", "")
                            .replace("：", "")
                            .trim()
                            ;
                    orderDO.setRemark(remarkStr);
                    remarkLine = i;
                    break;
                }
            }
        }

        // 到货点
        Object arrivalPoint = list.get(managerLine - 1).get(10);
        if (arrivalPoint != null && !arrivalPoint.equals("")) {
            orderDO.setArrivalPoint(arrivalPoint.toString());
        }

        // 出货方式
        Object deliveryMode = list.get(managerLine - 1).get(11);
        if (deliveryMode != null && !deliveryMode.equals("")) {
            orderDO.setDeliveryMode(deliveryMode.toString());
        }

        // 厂长
        Object manager = list.get(managerLine + 1).get(9);
        if (manager != null && !manager.equals("")) {
            orderDO.setManager(manager.toString());
        }

        // 开发业务
        Object businessName = list.get(managerLine + 1).get(10);
        if (businessName != null && !businessName.equals("")) {
            orderDO.setBusinessName(businessName.toString());
        }

        // 经办
        Object operator = list.get(managerLine + 1).get(11);
        if (operator != null && !operator.equals("")) {
            orderDO.setOperator(operator.toString());
        }

        // 解析订单编号和订单日期
        // 订单编号
        Object orderCode = list.get(orderCodeLine).get(0);
        String orderCodeStr = "";
        if (orderCode != null && !orderCode.equals("")) {
            // orderCodeStr = orderCode.toString().replaceAll("[^\\d]", "");
            orderCodeStr = orderCode.toString().replace("：",":").replaceAll("\\s", "");
            String[] orderCodeArr = orderCodeStr.split(":");
            if (orderCodeArr.length == 2) {
                orderDO.setId(orderCodeArr[1]);
            }
            if (StringUtils.isBlank(orderDO.getId())) {
                throw new ServiceException(ERROR_STATUS, "订单编号不能为空");
            }
        }

        for (OrderDetailDO orderDetailDO : importDataList) {
            orderDetailDO.setOrderCode(orderDO.getId());
            orderDetailDO.setFullFlexName(orderDetailDO.getFlex());
            orderDetailDO.setDetailInfoJson(JSONObject.toJSONString(orderDetailDO));
        }

        // 订单日期
        Object dateStr = list.get(orderCodeLine).get(4);
        if (dateStr != null && !dateStr.equals("")) {
            String orderDateStr = dateStr.toString()
                    .replace("日期:", "")
                    .replaceAll("\\s*", "");
            orderDO.setDateStr(orderDateStr);
        }

        // 编号
        Object code = list.get(orderCodeLine).get(11);
        if (code != null && !code.equals("")) {
            orderDO.setCode(code.toString());
        }

        // 统一设置订单明细的订单编号
        for (OrderDetailDO orderDetailDO : importDataList) {
            orderDetailDO.setOrderCode(orderDO.getId());
            orderDetailDO.setId(orderDO.getId() + "_" + orderDetailDO.getPartId());
        }

        return orderDO;
    }

    @PostMapping("/pageOrderDetail")
    @Operation(summary = "获得生产调度订单详情分页")
    public CommonResult<PageResult<OrderDetailScheduledVO>> pageOrderDetail(@Valid @RequestBody OrderDetailPageReqVO pageReqVO) {
        PageResult<OrderDetailDO> pageResult = orderDetailService.selectOrderDetailPage(pageReqVO);

        PageResult<OrderDetailScheduledVO> result = BeanUtils.toBean(pageResult, OrderDetailScheduledVO.class);
        if (null != result) {
            List<OrderDetailScheduledVO> list = result.getList();
            if (CollectionUtil.isNotEmpty(list)) {
                for (OrderDetailScheduledVO orderDetailScheduledVO : list) {
                    String expiryDate = orderDetailScheduledVO.getExpiryDate();
                    orderDetailScheduledVO.setExpiryDateStr(expiryDate);
                }
            }
        }
        return success(result);
    }


    @GetMapping("/exportOrderDetail")
    @Operation(summary = "获得生产订单详情分页")
    public void  exportOrderDetail(@Valid OrderDetailPageReqVO pageReqVO, HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);

        //deliveryReceiptDetailMapper.selectList(new QueryWrapper<DeliveryReceiptDetailDO>().eq("out_dept_name", "C课").eq(""));

        PageResult<OrderDetailDO> pageResult = orderDetailService.selectOrderDetailPage(pageReqVO);
        PageResult<OrderDetailScheduledVO> result = BeanUtils.toBean(pageResult, OrderDetailScheduledVO.class);
        if (null != result) {
            List<OrderDetailScheduledVO> list = result.getList();
            if (CollectionUtil.isNotEmpty(list)) {
                for (OrderDetailScheduledVO orderDetailScheduledVO : list) {
                    String expiryDate = orderDetailScheduledVO.getExpiryDate();
                    orderDetailScheduledVO.setExpiryDateStr(expiryDate);
                }

                // 导出 Excel
                ExcelUtils.write(response, "生产订单明细信息.xls", "数据", OrderDetailScheduledVO.class,
                        list);
            }
        }
    }

    @GetMapping("/queryOrderFlexList")
    @Operation(summary = "获得订单规格列表")
    public CommonResult<List<String>>  queryOrderFlexList(@RequestParam("orderCode")String orderCode) throws IOException {
        List<String> list = orderDetailService.queryOrderFlexList(orderCode);
        return success(list);
    }



}